const Joi = require('joi')
const R = require('@/models/Response')
const { Role } = require('@/models/model')
const { ERROR_USER_CODE, ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const { DATE_FORMAT_ARR } = require('@/constants')
const {
  IS_INTEGER,
  IS_UNSAFE_INTEGER_2,
  IS_UNSAFE_INTEGER
} = require('@/constants/joiSchema')

// 系统配置验证模型
const systemSchema = {
  dataFormat: Joi.string(),
  pwdLock: IS_INTEGER.valid(0, 1),
  loginValidateCode: IS_INTEGER.valid(0, 1),
  msgValidateCode: IS_INTEGER.valid(0, 1),
  pwdLevel: IS_INTEGER.valid(0, 1, 2),
  userRegister: IS_INTEGER.valid(0, 1),
  chunkSize: IS_INTEGER.min(0).max(1073741824),
  uploadThreadNum: IS_INTEGER.min(1).max(100),
  requestRetryNum: IS_INTEGER.min(1).max(10),
  defaultRoleId: IS_UNSAFE_INTEGER,
  defaultSizeMax: IS_INTEGER.min(0).max(107374182400),
  depSizeMax: IS_UNSAFE_INTEGER_2.min(0).max(1099511627776),
  uploadIngoreSources: Joi.string().allow(''),
  emailType: IS_INTEGER.valid(0, 1),
  emailServer: Joi.string().allow(''),
  emailAddr: Joi.string().allow(''),
  emailEncrpyType: IS_INTEGER.valid(0, 1),
  emailAuthPwd: Joi.string().allow(''),
  isLinkShow: IS_INTEGER.valid(0, 1),
  isLink: IS_INTEGER.valid(0, 1),
  isLinkPwdAllowEmpty: IS_INTEGER.valid(0, 1),
  isLinkAllowNotLogin: IS_INTEGER.valid(0, 1),
  isLinkPackDownload: IS_INTEGER.valid(0, 1),
  sourceMd5Show: IS_INTEGER.valid(0, 1),
  thirdPartLogin: Joi.string().allow(''),
  userRegisterCheck: IS_INTEGER.valid(0, 1),
  companyName: Joi.string().allow(''),
  companySubName: Joi.string().allow(''),
  ingoreSources: Joi.string().allow(''),
  newUserDefaultSources: Joi.string().allow(''),
  defaultDepInfo: Joi.string()
}

const validCheck = {
  checkDataForm: (date) => {
    if (DATE_FORMAT_ARR.includes(date)) {
      return true
    } else {
      return false
    }
  }
}

module.exports.setSystemOptValidate = async (ctx, next) => {
  // 校验参数格式
  const schema = Joi.object(systemSchema).validate(ctx.request.body)
  // 参数校验失败
  if (schema.error) {
    console.log(schema.error)
    ctx.body = R.error(ERROR_USER_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  // TODO检验roleID是否合法
  const { defaultRoleId, dataFormat } = ctx.request.body
  if (defaultRoleId) {
    const role = await Role.findOne({
      where: {
        id: BigInt(defaultRoleId),
        type: 0
      }
    })
    if (!role) {
      ctx.body = R.error(ERROR_USER_CODE.SYSTEM_ROLE_ERROR)
      return
    }
  }
  // 检验dataFormat的合法性
  if (dataFormat) {
    if (!validCheck.checkDataForm(dataFormat)) {
      ctx.body = R.error(ERROR_SYSTEM_CODE.DATE_FORMAT_ERROR)
      return
    }
  }
  await next()
}
